<template>
  <div>
    <el-dialog v-model="deviceDialog.visible.value" :title="deviceDialog.title.value" width="1300px" append-to-body destroy-on-close>
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="90px">
          <el-form-item label="设备名称" prop="equipmentName">
            <el-input v-model="queryParams.equipmentName" placeholder="请输入用户名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="设备识别码" prop="deviceId">
            <el-input v-model="queryParams.deviceId" placeholder="请输入设备标识" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="连接状态" prop="onlineStatus">
            <el-select v-model="queryParams.deviceStatus" placeholder="请选择设备状态" clearable>
              <el-option v-for="dict in equipment_online_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="() => resetQuery()">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card shadow="hover" style="height: 530px; margin-top: 6px;">
        <template #header>
          <el-tag v-for="device in selectDeviceList" :key="device.equipmentId" closable style="margin: 2px" @close="handleCloseTag(device)">
            {{ device.equipmentName }}
          </el-tag>
        </template>

        <vxe-table
          ref="tableRef"
          height="416px"
          border
          show-overflow
          :data="deviceList"
          :loading="deviceLoading || selectDeviceLoading"
          :row-config="{ keyField: 'equipmentId', isHover: true }"
          :checkbox-config="{ checkMethod: ({ row }) => { return prop.disableCheck == false || row.equipmentTypeLevel1Id == null }, reserve: true, trigger: 'row', highlight: true, showHeader: prop.multiple }"
          @checkbox-all="handleCheckboxAll"
          @checkbox-change="handleCheckboxChange"
        >
          <vxe-column type="checkbox" width="50" align="center" />
          <vxe-column key="equipmentName" field="equipmentName" title="设备名称" align="center" min-width="160px" />
          <vxe-column key="deviceId" field="deviceId" title="设备识别码" align="center" min-width="160px" />
          <vxe-column key="equipmentTypeLevel1Name" field="equipmentTypeLevel1Name" title="设备一级类型" align="center" min-width="120px" />
          <vxe-column key="equipmentTypeLevel2Name" field="equipmentTypeLevel2Name" title="设备二级类型" align="center" min-width="120px" />
          <vxe-column key="productName" field="productName" title="设备型号" align="center" min-width="120px" />
          <vxe-column title="设备位置" align="center" min-width="160px" >
            <template #default="scope">
              {{ getParkPositionStr(scope.row.parkBuildingName, scope.row.parkBuildingAreaName, scope.row.parkBuildingFloorName, scope.row.parkBuildingRoomName) }}
            </template>
          </vxe-column>
          <vxe-column title="连接状态" align="center" width="100px">
            <template #default="scope">
              <dict-tag :options="equipment_online_status" :value="scope.row.deviceStatus" />
            </template>
          </vxe-column>
          <vxe-column title="设备状态" align="center" width="100px">
            <template #default="scope">
              <dict-tag :options="equipment_status" :value="scope.row.status" />
            </template>
          </vxe-column>
        </vxe-table>

        <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="pageList" />
      </el-card>

      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { UserVO } from '@/api/system/user/types';
import { VxeTableInstance } from 'vxe-table';
import useDialog from '@/hooks/useDialog';
import { getParkPositionStr } from '@/utils/parkUtil'
import request from '@/utils/request';

interface PropType {
  modelValue?: any;
  multiple?: boolean;
  data?: any;
  disableCheck?: any;
  dataSource?: any
}
const prop = withDefaults(defineProps<PropType>(), {
  multiple: true,
  modelValue: undefined,
  data: undefined,
  disableCheck: true,
  dataSource: 1
});
const emit = defineEmits(['update:modelValue', 'confirmCallBack']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, equipment_status, equipment_online_status } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'equipment_status', 'equipment_online_status'));

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const selectDeviceList = ref<any[]>([]);

const queryFormRef = ref<ElFormInstance>();
const tableRef = ref<VxeTableInstance<UserVO>>();

const deviceDialog = useDialog({
  title: '设备选择'
});

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  equipmentName: '',
  deviceId: '',
  dataSource: prop.dataSource
});

const confirm = () => {
  emit('update:modelValue', selectDeviceList.value);
  emit('confirmCallBack', selectDeviceList.value);
  deviceDialog.closeDialog();
};

const computedIdList = (data) => {
  if (data instanceof Array) {
    return [...data];
  } else if (typeof data === 'string') {
    return data.split(',');
  } else if (typeof data === 'number') {
    return [data];
  }

  return [];
};

/** 查询设备列表 */
const deviceList = ref<any[]>();
const deviceLoading = ref(false);
const total = ref(0);
const getList = async () => {
  deviceLoading.value = true;
  const res = await request({ url: '/equipment/equipment-info/list', method: 'get', params: queryParams.value }).finally(() => { deviceLoading.value = false; })
  deviceList.value = res.rows;
  total.value = res.total;

  console.log('获取设备列表：', deviceList.value);
};

/**
 * 初始化已选设备
 */
const selectDeviceLoading = ref(false);
const defaultSelectDeviceIdList = computed(() => computedIdList(prop.data));
const initSelectDevice = async () => {
  if (defaultSelectDeviceIdList.value.length > 0) {
    selectDeviceLoading.value = true;
    const res = await request({ url: '/equipment/equipment-info/list', method: 'get', params: { equipmentIdList: defaultSelectDeviceIdList.value }}).finally(() => { selectDeviceLoading.value = false; })
    console.log('初始化已选设备：', res);

    selectDeviceList.value = res.rows;
    const selectedDeviceList = deviceList.value.filter((item) => {
      return defaultSelectDeviceIdList.value.includes(String(item.equipmentId));
    });

    // 选中已选设备
    await nextTick(() => {
      tableRef.value.setCheckboxRow(selectedDeviceList, true);
    });
  }
};

const pageList = async () => {
  await getList();
  const selectedDeviceList = deviceList.value.filter((item) => {
    return selectDeviceList.value.some((user) => user.equipmentId === item.equipmentId);
  });
  await tableRef.value.setCheckboxRow(selectedDeviceList, true);
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = (refresh = true) => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  refresh && handleQuery();
};

const handleCheckboxChange = (checked) => {
  if (!prop.multiple && checked.checked) {
    tableRef.value.setCheckboxRow(selectDeviceList.value, false);
    selectDeviceList.value = [];
  }
  const row = checked.row;
  if (checked.checked) {
    selectDeviceList.value.push(row);
  } else {
    selectDeviceList.value = selectDeviceList.value.filter((item) => {
      return item.equipmentId !== row.equipmentId;
    });
  }
};
const handleCheckboxAll = (checked) => {
  const rows = deviceList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectDeviceList.value.some((item) => item.equipmentId === row.equipmentId)) {
        selectDeviceList.value.push(row);
      }
    });
  } else {
    selectDeviceList.value = selectDeviceList.value.filter((item) => {
      return !rows.some((row) => row.equipmentId === item.equipmentId);
    });
  }
};

const handleCloseTag = (user: any) => {
  const equipmentId = user.equipmentId;
  // 使用split删除用户
  const index = selectDeviceList.value.findIndex((item) => item.equipmentId === equipmentId);
  const rows = selectDeviceList.value[index];
  tableRef.value?.setCheckboxRow(rows, false);
  selectDeviceList.value.splice(index, 1);
};

const close = () => {
  deviceDialog.closeDialog();
};

watch(
  () => deviceDialog.visible.value, async (newValue: boolean) => {
    if (newValue) {
      await getList(); // 初始化列表数据
      await initSelectDevice();
    } else {
      tableRef.value.clearCheckboxReserve();
      tableRef.value.clearCheckboxRow();
      resetQuery(false);
      selectDeviceList.value = [];
    }
  }
);

defineExpose({
  open: deviceDialog.openDialog,
  close: deviceDialog.closeDialog
});
</script>
<style lang="scss" scoped>
  :deep(.el-dialog) {
    height: 750px !important;
  }
</style>
